<?php
namespace App\Admin\Controllers\Traits\WxSettingTraits;

use App\Admin\Renderable\UsersRender;
use App\Models\User\WxUser;
use App\Wen\Utils\AdminUtils;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\SiteUtils;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

trait formSafeTrait{
    public function index_safe(Content $content)
    {
        return $content->title('安全配置')
//            ->body($this->buildPreviewButton())
//            ->body($this->newline())
            ->body(
                <<<HTML
<div class="card">{$this->form_safe()->render()}</div>
HTML
            );
    }
    protected function form_safe(){
        $form = new Form();
        $form->confirm('您确定要提交表单吗？', 'content');
        $form->disableResetButton();
        $form->tab('管理', function (Form $form) {



            $form->html(function () {
                return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">说明: <br>这里配置是在App小程序端生效，后台与app并不是一套用户体系，后台的权限控制在：<a href="'.admin_url('auth/users').'" target="_blank">[开发配置-团队]</a></div>';
            }, '');
            $form->multipleSelectTable('app_admin_super_admin', '超级管理员')
                ->title('用户')
                ->max(100)
                ->from(UsersRender::make())
                ->model(WxUser::class, 'id', 'user_name', 'selectTable:formSafeTrait:app_admin_super_admin')
                ->help('超级管理员比普通管理员拥有更多的权限，比如马甲，设置为超级管理员时，会同时增加普通管理员，普通管理员在<a href="'.admin_url('users').'" target="_blank">[用户管理-用户]</a>可以自行管理。<a href="https://doc.minisns.cn/doc/70/" target="_blank" style="color: red;">（ps：如何控制顺序?）&nbsp;</a>')
                ->default(Settings::get('app_admin_super_admin', '', true));
            $form->multipleSelectTable('app_admin_played_users', '马甲账号')
                ->title('用户')
                ->max(100)
                ->from(UsersRender::make())
                ->model(WxUser::class, 'id', 'user_name', 'selectTable:formSafeTrait:app_admin_played_users')
                ->help('需要超级管理员权限才可以使用这些马甲账号<a href="https://doc.minisns.cn/doc/70/" target="_blank" style="color: red;">（ps：如何控制顺序?）&nbsp;</a>')->default(Settings::get('app_admin_played_users', '', true));

        });

        global $__MINI_GLOBAL_TENANT_ID__;
        if($__MINI_GLOBAL_TENANT_ID__ === 0){
            $form->tab('三方服务', function (Form $form) {
                $form->html(function () {
                    return '<div style="color: red;padding: 10px;border-radius: 5px;">*** 请勿泄露access_token ***</div>';
                }, '');
                $form->text('mini_access_token', 'access_token')->help('access_token用来对外部的请求进行安全校验，只有access_token匹配的情况下，第三方程序才能请求mini提供服务，access_token为url参数，不是body参数，请看<a href="" target="_blank">示例</a>')->default(Settings::get('mini_access_token', '', true));
            });
        }


        $form->action('settings/action/safe');
        return $form;
    }

    public function safe(Request $request){
        SiteUtils::forget_config_data();
        Cache::forget(_multi_key('admin_played_users'));
        $app_admin_super_admin = $request->input('app_admin_super_admin');
        if($app_admin_super_admin){
            global $__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                foreach (explode(',', $app_admin_super_admin) as $user_id){
                    if($user_id > 0){
                        update_user_meta($user_id, 'tenant_id_'.$__MINI_GLOBAL_TENANT_ID__, 1, 'n');
                    }
                }
            }else{
                WxUser::whereIn('id', explode(',', $app_admin_super_admin))->update(['is_official'=>1]);
                _update_env([
                    'APP_SUPER_ADMIN_USER_ID' => implode(',', (explode(',', $app_admin_super_admin) ?: [])),
                ], [], 1);
            }
        }

        $app_admin_played_users = $request->input('app_admin_played_users');
        if($app_admin_played_users){
            $admin_played_users = WxUser::whereIn('id',explode(',', $app_admin_played_users))->get(['id', 'user_name', 'user_avatar']);
            Cache::put(_multi_key('admin_played_users'), json_encode($admin_played_users));
        }

        Settings::set('app_admin_super_admin', AdminUtils::_multipleSelectTable_order_process('selectTable:formSafeTrait:app_admin_super_admin', $app_admin_super_admin), true, true);
        Settings::set('app_admin_played_users', AdminUtils::_multipleSelectTable_order_process('selectTable:formSafeTrait:app_admin_played_users', $app_admin_played_users), true, true);
        global $__MINI_GLOBAL_TENANT_ID__;
        if($__MINI_GLOBAL_TENANT_ID__ === 0){
            Settings::set('mini_access_token', $request->input('mini_access_token'), true, true);
        }

        $__global_config_version__ = Settings::get('__global_config_version__', 1) + 1;
        Settings::set('__global_config_version__', $__global_config_version__);
        GatewayUtils::success('all', 13, [ 'version' => $__global_config_version__, 'file' => basename(__FILE__) ]);
        return $this->response()->success('成功！');
    }

}
